//
//  OrderConfirmViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-9-24.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "OrderConfirmViewController.h"
#import "OrderSuccessViewController.h"
#import "ZhiFuTypeCell.h"

//支付宝客户端头文件
#import "DataSigner.h"
#import "AlixPayResult.h"
#import "DataVerifier.h"
#import "AlixPayOrder.h"
#import "PartnerConfig.h"
#import "AlixLibService.h"

#import "PayByBagViewController.h"


@interface OrderConfirmViewController ()
{
    NSString * goodPrice;
    BOOL chooseZhiFuType;  //no是客户端 yes是网页
}
@end

@implementation OrderConfirmViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backPrePage{
    
//    [XDTools sharedXDTools].OrderConfirmVC = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [XDTools sharedXDTools].orderDetailVC = nil;
    isFirst = YES;
    chooseZhiFuType = NO;
    self.titleLabel.text = @"订单确认";
    voucherID = [[NSString alloc] init];
    voucherID= @"";
    goodPrice = [NSString stringWithFormat:@"%@",[XDTools sharedXDTools].taocanPrcie];
    sel = @selector(paymentResult:);

    backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT)];
    backScrollView.delegate = self;
    [self.contentView addSubview:backScrollView];

    UIView * headView = [self createHeader];
    
    UIView * middleView = [self createMiddleViewWithHeight:height_y(headView)];
    UIView * downView = [self createDownViewWithHeight:height_y(middleView)];

    UILabel * label = [UILabel initLabelText:[NSString stringWithFormat:@"应付金额: ￥%@",[XDTools sharedXDTools].taocanPrcie] andRect:CGRectMake(0, height_y(downView)+15, UI_SCREEN_WIDTH, 25) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:14] andTextColor:RGBA(48, 44, 39, 1) andTextAlignment:NSTextAlignmentCenter];
    label.tag = 23456;
    label.attributedText = [XDTools getAcolorfulStringWithTextArray:@[[NSString stringWithFormat:@"￥%@",[XDTools sharedXDTools].taocanPrcie]] Color:RGBA(255, 42, 0, 1) Font:[UIFont systemFontOfSize:18] AllText:label.text];

    [backScrollView addSubview:label];

    UILabel * label2 = [UILabel initLabelText:@"如有质量问题，全额退款。" andRect:CGRectMake(0,height_y(label)+5,UI_SCREEN_WIDTH,15) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:11] andTextColor:RGBA(184, 184, 184, 1) andTextAlignment:NSTextAlignmentCenter];
    [backScrollView addSubview:label2];

    
    
    //选择支付方式
    UILabel * l = [UILabel initLabelText:@"选择支付方式" andRect:CGRectMake(8,height_y(label2)+20,200,15) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:15] andTextColor:UIColorFromRGB(0x888888) andTextAlignment:NSTextAlignmentLeft];
    [backScrollView addSubview:l];
    
    UITableView * mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, height_y(l)+8, UI_SCREEN_WIDTH, 100) style:UITableViewStylePlain];
    mTableView.backgroundColor = mClearColor;
    mTableView.delegate =self;
    mTableView.dataSource= self;
    mTableView.bounces = NO;
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [backScrollView addSubview:mTableView];
    
    
    UIView * btnBg = [UIView initViewRect:CGRectMake(0,self.view.frame.size.height-70, UI_SCREEN_WIDTH, 70) andBackGroudColor:self.contentView.backgroundColor];
    [self.view addSubview:btnBg];
    
    UIView * line = [UIView initViewRect:CGRectMake(0, 0,UI_SCREEN_WIDTH, 0.5) andBackGroudColor:UIColorFromRGB(0xd4ccc5)];
    [btnBg addSubview:line];

    UIImage * image = [UIImage imageNamed:@"orangeBtn"];  //上左下右
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10,10,10,10)];

    UIButton * confirmBtn = [UIButton initButton:CGRectMake(45,15, 230, 40) btnImage:LOADIMAGE(@"xiadan@2x") btnTitle:@"订单确认" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [confirmBtn addTarget:self action:@selector(confirmOrder) forControlEvents:UIControlEventTouchUpInside];
    [btnBg addSubview:confirmBtn];


    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, height_y(label2)+80+170);


    [self getDataWithDict:@{@"CustomerID":[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID] } api:API_GETYOUHUIQUAN];

}



-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{
    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
        
    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        
        [XDTools hideProgress:self.contentView];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        
        DDLOG(@"temdic = %@",tempDic);
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            
            BOOL haveYouhuiquan = NO;
            for (NSDictionary * dict in tempDic[@"data"]) {
                if ([dict[@"status"] intValue] == 2) {
                    haveYouhuiquan = YES;
                    [XDTools sharedXDTools].haveYouHuiQuan = YES;
                    break;
                }
            }
            
            if (!haveYouhuiquan) {
                [XDTools sharedXDTools].haveYouHuiQuan = NO;
            }
            [self reloadYouhuiquanInfo];
            
        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.contentView];
        }
        
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

- (UIView *)createHeader{
    UIView * headView = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 96) andBackGroudColor:RGBA(243, 243, 243, 1)];
    [backScrollView addSubview:headView];
    
    NSArray * array = @[@"手  机  号:",@"预约时间: ",@"拍摄地址: "];
    if (!IS_NOT_EMPTY([XDTools sharedXDTools].iphoneNumber)) {
        [XDTools sharedXDTools].iphoneNumber = @"13988888888";
    }
    if (!IS_NOT_EMPTY([XDTools sharedXDTools].time)) {
        [XDTools sharedXDTools].time = @"2014-10-30";
    }
    if (!IS_NOT_EMPTY([XDTools sharedXDTools].adderss)) {
        [XDTools sharedXDTools].adderss = @"jhadshjasjhd";
    }
    NSArray * array2 = @[[XDTools sharedXDTools].iphoneNumber,[XDTools sharedXDTools].time,[XDTools sharedXDTools].adderss];
    for (int i = 0; i < 3; i++) {
        UILabel * label = [UILabel initLabelText:array[i] andRect:CGRectMake(10, 13+25*i, 75, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:RGBA(153, 153, 153, 1) andTextAlignment:NSTextAlignmentLeft];

        UILabel * label2 = [UILabel initLabelText:array2[i] andRect:CGRectMake(VIEW_POINT_MAX_X(label), 13+25*i, 200, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:RGBA(48, 44, 39, 1) andTextAlignment:NSTextAlignmentLeft];
        label2.numberOfLines = 0;

        [headView addSubview:label];
        [headView addSubview:label2];

        if (i == 2) {
            [label2 sizeToFit];
            headView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, height_y(label2)+10);

            UIView * line = [UIView initViewRect:CGRectMake(0, height_y(label2)+9.5f, UI_SCREEN_WIDTH, .5f) andBackGroudColor:RGBA(200, 200, 200, 1)];
            [headView addSubview:line];
        }

    }

    return headView;
}

- (UIView *)createMiddleViewWithHeight:(float)height{
    UIView * middleView = [UIView initViewRect:CGRectMake(0, height+10, UI_SCREEN_WIDTH, 220) andBackGroudColor:[UIColor whiteColor]];
    [backScrollView addSubview:middleView];

    for (int i = 0; i < 2; i++) {
        UIView * line = [UIView initViewRect:CGRectMake(0, i*219.5f, UI_SCREEN_WIDTH, .5f) andBackGroudColor:RGBA(200, 200, 200, 1)];
        [middleView addSubview:line];
    }

    UIView * line = [UIView initViewRect:CGRectMake(0, 80, UI_SCREEN_WIDTH, .5f) andBackGroudColor:RGBA(200, 200, 200, 1)];
    [middleView addSubview:line];


    //套餐views
    taocanIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 60, 60)];
    taocanIV.backgroundColor = UIColorFromRGB(0xeaeaea);
    taocanIV.layer.masksToBounds = YES;
    taocanIV.layer.cornerRadius = 30;
    taocanIV.contentMode = UIViewContentModeScaleAspectFill;
    [taocanIV sd_setImageWithURL:[NSURL URLWithString:[XDTools sharedXDTools].taocanImgUrl] placeholderImage:ivDetaultImg];
    [middleView addSubview:taocanIV];

    taocanNameLB = [UILabel initLabelText:[XDTools sharedXDTools].taocanName andRect:CGRectMake(VIEW_POINT_MAX_X(taocanIV)+15,13,200,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:17] andTextColor:RGBA(48, 44, 39, 1) andTextAlignment:NSTextAlignmentLeft];
    [middleView addSubview:taocanNameLB];
    
    priceLB = [UILabel initLabelText:[[NSString alloc] initWithFormat:@"￥%@",[XDTools sharedXDTools].taocanPrcie] andRect:CGRectMake(VIEW_POINT_MAX_X(taocanIV)+15,height_y(taocanNameLB)+5,100,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:17] andTextColor:UIColorFromRGB(0xff8276) andTextAlignment:NSTextAlignmentLeft];
    [priceLB sizeToFit];
    [middleView addSubview:priceLB];

    marketPriceLB = [UILabel initLabelText:[[NSString alloc] initWithFormat:@"￥%@",[XDTools sharedXDTools].taocanMarketPrice] andRect:CGRectMake(width_x(priceLB)+10, height_y(taocanNameLB)+8, 80, 16) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:13] andTextColor:UIColorFromRGB(0x999999) andTextAlignment:NSTextAlignmentLeft];
    [middleView addSubview:marketPriceLB];
    
    shortLine = [UIView initViewRect:CGRectMake(marketPriceLB.frame.origin.x-2, marketPriceLB.frame.origin.y+7, 8.5*marketPriceLB.text.length, 1) andBackGroudColor:UIColorFromRGB(0x999999)];
    [middleView addSubview:shortLine];


    //摄影师views
    cameraManIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 90, 60, 60)];
    cameraManIV.layer.masksToBounds = YES;
    cameraManIV.layer.cornerRadius = 30;
    cameraManIV.backgroundColor = UIColorFromRGB(0xeaeaea);
    [cameraManIV sd_setImageWithURL:[NSURL URLWithString:[XDTools sharedXDTools].emplImgUrl] placeholderImage:LOADIMAGE(@"placeholderHeader@2x")];
    [middleView addSubview:cameraManIV];

    cameraManNameLB = [UILabel initLabelText:[XDTools sharedXDTools].emplName andRect:CGRectMake(VIEW_POINT_MAX_X(taocanIV)+15,height_y(line)+15,80,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:16] andTextColor:RGBA(48, 44, 39, 1) andTextAlignment:NSTextAlignmentLeft];
    [cameraManNameLB sizeToFit];
    [middleView addSubview:cameraManNameLB];

    levelLB = [UILabel initLabelText:[XDTools sharedXDTools].emplLevel andRect:CGRectMake(VIEW_POINT_MAX_X(cameraManNameLB)+15,height_y(line)+15,80,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:RGBA(129, 118, 108, 1) andTextAlignment:NSTextAlignmentLeft];
    [middleView addSubview:levelLB];
    
    if ([XDTools sharedXDTools].emplGouTong){
    
    }else{
        [XDTools sharedXDTools].emplZhuanYe = @"5.0";
        [XDTools sharedXDTools].emplGouTong = @"5.0";
        [XDTools sharedXDTools].emplShoushi = @"5.0";
    }
    scoreLB = [UILabel initLabelText:[[NSString alloc] initWithFormat:@"专业：%@  沟通：%@  守时：%@",[XDTools sharedXDTools].emplZhuanYe,[XDTools sharedXDTools].emplGouTong,[XDTools sharedXDTools].emplShoushi] andRect:CGRectMake(VIEW_POINT_MAX_X(taocanIV)+15,height_y(cameraManNameLB)+5,200,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:13] andTextColor:RGBA(110, 94, 81, 1) andTextAlignment:NSTextAlignmentLeft];
    scoreLB.attributedText = [XDTools getAcolorfulStringWithTextArray:@[@"专业：",@"沟通：",@"守时："] Color:RGBA(179, 179, 179, 1) Font:scoreLB.font AllText:scoreLB.text];
    [middleView addSubview:scoreLB];

    UIView * line1 = [[XDTools sharedXDTools] createSeparatorLineWithRect:CGRectMake(0, height_y(cameraManIV)+10, UI_SCREEN_WIDTH, .5f)];
    [middleView addSubview:line1];

    UIImageView * roundBg = [[UIImageView alloc] initWithFrame:CGRectMake(10, height_y(cameraManIV)+20, UI_SCREEN_WIDTH-20, 40)];
    roundBg.backgroundColor = UIColorFromRGB(0xeaeaea);
    roundBg.layer.masksToBounds = YES;
    roundBg.layer.cornerRadius = 15;
    [middleView addSubview:roundBg];

    messageTF = [[UITextField alloc] initWithFrame:CGRectMake(27.5, height_y(cameraManIV)+30, UI_SCREEN_WIDTH-55, 20)];
    messageTF.delegate = self;
    messageTF.placeholder = @"给摄影师留言";
    messageTF.font = [UIFont systemFontOfSize:15];
    messageTF.returnKeyType  =  UIReturnKeyDone;
    [middleView addSubview:messageTF];

    return middleView;
}

- (UIView *)createDownViewWithHeight:(float)height{
    UIView * downView = [UIView initViewRect:CGRectMake(0, height+10, UI_SCREEN_WIDTH, 44.5f) andBackGroudColor:[UIColor whiteColor]];
    [backScrollView addSubview:downView];

    for (int i = 0; i < 2; i++) {
        UIView * line = [UIView initViewRect:CGRectMake(0, i*44, UI_SCREEN_WIDTH, .5f) andBackGroudColor:RGBA(200, 200, 200, 1)];
        [downView addSubview:line];
    }

    UILabel * lb1 = [UILabel initLabelText:@"优惠券 有可用优惠券" andRect:CGRectMake(10,12,230,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:16] andTextColor:RGBA(48, 44, 39, 1) andTextAlignment:NSTextAlignmentLeft];
    lb1.tag = 123712;
    [downView addSubview:lb1];
    
    UILabel * label = [UILabel initLabelText:@"未使用" andRect:CGRectMake(242, 12, 45, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:RGBA(255, 42, 0, 1) andTextAlignment:NSTextAlignmentLeft];
    label.tag = 12345;
    [downView addSubview:label];
    
    UIImageView * arrow = [[UIImageView alloc] initWithFrame:CGRectMake(295, 16, 15/2.0f, 25/2.0f)];
    arrow.image = [UIImage imageNamed:@"arrow_cell"];
    [downView addSubview:arrow];
    
    UIButton * btn = [UIButton initButton:CGRectMake(0, 0, UI_SCREEN_WIDTH, 44) btnNorImage:nil btnHighlightImage:nil btnTitle:nil titleColor:[UIColor clearColor] titleFont:nil];
    [btn addTarget:self action:@selector(useYouHuiQuan) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 817234;
    [downView addSubview:btn];
    
    if (![XDTools sharedXDTools].haveYouHuiQuan) {
        lb1.text = @"优惠券 无可用优惠券";
        btn.userInteractionEnabled = NO;
    }

    return downView;
}

- (void)reloadYouhuiquanInfo{
    UIButton * btn = (UIButton *)[self.view viewWithTag:817234];
    UILabel * lab = (UILabel *)[self.view viewWithTag:123712];
    if (![XDTools sharedXDTools].haveYouHuiQuan) {
        lab.text = @"优惠券 无可用优惠券";
        btn.userInteractionEnabled = NO;
    }else{
        lab.text = @"优惠券 有可用优惠券";
        btn.userInteractionEnabled = YES;
    }
}


#pragma mark
#pragma mark UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    ZhiFuTypeCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil){
        cell = [[ZhiFuTypeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row == 0){
        cell.zhifuiconIV.image = LOADIMAGE(@"alipayClientIcon@2x");
        cell.titleLB.text = @"支付宝客户端支付";
        cell.contentLB.text = @"推荐已安装支付宝客户端的用户使用";
        if (chooseZhiFuType){
            cell.chooseBtn.enabled = YES;
        }else{
            cell.chooseBtn.enabled =NO;
        }
        cell.downline.hidden = NO;
    }else{
        cell.zhifuiconIV.image = LOADIMAGE(@"alipayWapIcon@2x");
        cell.titleLB.text = @"支付宝网页支付";
        cell.contentLB.text = @"推荐有支付宝账号的用户使用";
        if (chooseZhiFuType){
            cell.chooseBtn.enabled = NO;
        }else{
            cell.chooseBtn.enabled =YES;
        }
        cell.downline.hidden = YES;
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row){
        chooseZhiFuType = YES;
    }else{
        chooseZhiFuType = NO;
    }
    [tableView reloadData];
}

//-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    ZhiFuTypeCell * cell = (ZhiFuTypeCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
//    cell.chooseBtn.enabled = YES;
//}

- (void)useYouHuiQuan{
    YouHuiQuanViewController * youhuiquan = [[YouHuiQuanViewController alloc] init];
    youhuiquan.delegate = self;
    [self.navigationController pushViewController:youhuiquan animated:YES];
}


//确认订单
- (void)confirmOrder{
    
    if (!chooseZhiFuType) {
        BOOL yy =  [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]];
        
        if (!yy) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付提示" message:@"支付失败，检测到您的设备没有安装支付宝，请选择其他支付方式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
            
            return;
        }
    }
    
    [self checkOrder];
}


#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:.3f animations:^{
        backScrollView.contentOffset = CGPointMake(0, 200);
    }];
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [UIView animateWithDuration:.3f animations:^{
        backScrollView.contentOffset = CGPointMake(0, 30);
    }];
    return YES;
}

#pragma mark - UIScrollView Dlegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.isDragging) {
        [messageTF resignFirstResponder];
        
    }
}

#pragma mark
#pragma mark 提交订单
-(void)postOrder
{
    if (isFirst) {
        if (![XDTools NetworkReachable]){
            [XDTools showTips:brokenNetwork toView:self.view];
            return;
        }
        
        if(!(IS_NOT_EMPTY(messageTF.text))){
            messageTF.text = @"";
        }
        
        NSString * shoottype=[[NSString alloc] init];
        NSString * tmpstr = [[[XDTools sharedXDTools].time componentsSeparatedByString:@" "] lastObject];
        if ([tmpstr isEqualToString:@"上午"]){
            shoottype = @"AM";
        }else if ([tmpstr isEqualToString:@"下午"]){
            shoottype = @"PM";
        }else{
            shoottype = tmpstr;
        }
        NSDictionary * parms;
        if (IS_NOT_EMPTY([XDTools sharedXDTools].PSID)){
            parms = @{@"SceneID":[XDTools sharedXDTools].SceneID,
                      @"CustomerID":[XDTools sharedXDTools].CustomerID,
                      @"EmplID":[XDTools sharedXDTools].EmplID,
                      @"SeriesID":[XDTools sharedXDTools].SeriesID,
                      @"CityID":BJcityID,
                      @"ShootDate":[XDTools sharedXDTools].ShootDate,
                      @"ShootAddr":[XDTools sharedXDTools].ShootAddr,
                      @"ModeID":[XDTools sharedXDTools].ModeID,
                      @"content":messageTF.text,
                      @"PSID":[XDTools sharedXDTools].PSID,
                      @"VoucherID":voucherID,
                      @"ShootType":shoottype
                      };
        }else{
            parms = @{@"SceneID":[XDTools sharedXDTools].SceneID,
                      @"CustomerID":[XDTools sharedXDTools].CustomerID,
                      @"EmplID":[XDTools sharedXDTools].EmplID,
                      @"SeriesID":[XDTools sharedXDTools].SeriesID,
                      @"CityID":BJcityID,
                      @"ShootDate":[XDTools sharedXDTools].ShootDate,
                      @"ShootAddr":[XDTools sharedXDTools].ShootAddr,
                      @"ModeID":[XDTools sharedXDTools].ModeID,
                      @"content":messageTF.text,
                      @"VoucherID":voucherID,
                      @"ShootType":shoottype
                      };
        }
        
        ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:API_addOrder];
        __weak ASIHTTPRequest * mrequest = request;
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
            if ([tmpDict[@"status"] intValue]==1){
                
                _orderID = tmpDict[@"data"][@"OrderID"];
                isFirst = NO;
                
                [self checkOrderTime];
                
            }else{
                [XDTools showTips:tmpDict[@"msg"] toView:self.view];
            }
        }];
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            [XDTools showTips:networkovertime toView:self.view];
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
        
    }else{
        
        [self checkOrderTime];
        
    }
    

}


-(void)checkOrderTime
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    
    
    NSDictionary * parms = @{@"OrderID":_orderID};
    
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:API_CHECKORDERTIME];
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            
            [XDTools sharedXDTools].OrderConfirmVC = self;
            if(chooseZhiFuType){  //网页支付
                [self payByWeb];
            }else{  //客户端支付
                [self payByKeHuDuan];
            }
            
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
    
}


-(void)checkOrder
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    if(!(IS_NOT_EMPTY(messageTF.text))){
        messageTF.text = @"";
    }
    
    NSString * shoottype=[[NSString alloc] init];
    NSString * tmpstr = [[[XDTools sharedXDTools].time componentsSeparatedByString:@" "] lastObject];
    if ([tmpstr isEqualToString:@"上午"]){
        shoottype = @"AM";
    }else if ([tmpstr isEqualToString:@"下午"]){
        shoottype = @"PM";
    }else{
        shoottype = tmpstr;
    }
    NSDictionary * parms;
    if (IS_NOT_EMPTY([XDTools sharedXDTools].PSID)){
        parms = @{@"SceneID":[XDTools sharedXDTools].SceneID,
                  @"CustomerID":[XDTools sharedXDTools].CustomerID,
                  @"EmplID":[XDTools sharedXDTools].EmplID,
                  @"SeriesID":[XDTools sharedXDTools].SeriesID,
                  @"CityID":BJcityID,
                  @"ShootDate":[XDTools sharedXDTools].ShootDate,
                  @"ShootAddr":[XDTools sharedXDTools].ShootAddr,
                  @"ModeID":[XDTools sharedXDTools].ModeID,
                  @"content":messageTF.text,
                  @"PSID":[XDTools sharedXDTools].PSID,
                  @"VoucherID":voucherID,
                  @"ShootType":shoottype
                  };
    }else{
        parms = @{@"SceneID":[XDTools sharedXDTools].SceneID,
                  @"CustomerID":[XDTools sharedXDTools].CustomerID,
                  @"EmplID":[XDTools sharedXDTools].EmplID,
                  @"SeriesID":[XDTools sharedXDTools].SeriesID,
                  @"CityID":BJcityID,
                  @"ShootDate":[XDTools sharedXDTools].ShootDate,
                  @"ShootAddr":[XDTools sharedXDTools].ShootAddr,
                  @"ModeID":[XDTools sharedXDTools].ModeID,
                  @"content":messageTF.text,
                  @"VoucherID":voucherID,
                  @"ShootType":shoottype
                  };
    }
    
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:API_CHECKORDER];
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            
            [self postOrder];
            
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
    
}



- (void)willUseYouHuiQuan:(NSDictionary *)dict{
    UILabel * label = (UILabel *)[self.contentView viewWithTag:12345];
    label.text = @"已使用";
    
    float cheaper = [dict[@"VoucherPrice"] floatValue];
    float newPrice = [[XDTools sharedXDTools].taocanPrcie floatValue] - cheaper;
    if (newPrice < 0) {
        newPrice = 0;
    }
    goodPrice = [NSString stringWithFormat:@"%.2f",newPrice];
    UILabel * label2 = (UILabel *)[self.contentView viewWithTag:23456];
    label2.text = [NSString stringWithFormat:@"应付金额: ￥%.2f",newPrice];
    label2.attributedText = [XDTools getAcolorfulStringWithTextArray:@[[NSString stringWithFormat:@"￥%.2f",newPrice]] Color:RGBA(255, 42, 0, 1) Font:[UIFont systemFontOfSize:18] AllText:label2.text];
    
    voucherID = dict[@"VoucherID"];
}


//通过网页支付
-(void)payByWeb
{
    NSString * str0 = [NSString stringWithFormat:@"http://www.meike365.cn/index.php?m=Api&c=WapAlipay&a=doalipay&out_trade_no=%@&subject=%@&total_fee=%@",_orderID,[XDTools sharedXDTools].taocanName,goodPrice];
    NSString * payURL = [str0 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *malongUrl = [NSURL URLWithString:payURL];
    
    PayByBagViewController *payVC = [[PayByBagViewController alloc] init];
    payVC.webUrl = malongUrl;
    [self.navigationController pushViewController:payVC animated:YES];
    
}

//通过客户端
-(void)payByKeHuDuan{
    
    BOOL yy =  [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]];
    
    if (!yy) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付提示" message:@"支付失败，检测到您的设备没有安装支付宝，请选择其他支付方式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
    
    NSString *appScheme = @"com.xindao.meishimeike";
    NSString* orderInfo = [self getOrderInfo];
    NSString* signedStr = [self doRsa:orderInfo];
    
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                             orderInfo, signedStr, @"RSA"];
    NSLog(@"orderString:%@",orderString);
    
    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:sel target:self];
    
}

//支付宝回调
-(void)paymentResultDelegate:(NSString *)result{
    
}

-(void)paymentResult:(NSString *)result{
    
}
-(NSString*)getOrderInfo
{
    
    //拼接商品信息
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.partner = PartnerID;
    order.seller = SellerID;
    
    
    NSString *desc = [XDTools sharedXDTools].taocanDesc;
    
    if (!IS_NOT_EMPTY(desc)) {
        desc = @"专业的摄影";
    }
    
    
    order.productName = [XDTools sharedXDTools].taocanName;
    order.tradeNO = _orderID;  //订单ID（由商家自行制定）   ///需要赋值
    order.productDescription = desc;
    order.amount = goodPrice; //商品价格
    
    //测试的
//    order.amount = @"0.01";
    
//    order.notifyURL = @"http://123.57.16.119/index.php?m=Api&c=Order&a=notify&code=alipay"; //回调URL
    order.notifyURL = @"http://www.meike365.cn/call_back.php";
    
	return [order description];
}

-(NSString*)doRsa:(NSString*)orderInfo
{
    id<DataSigner> signer;
    signer = CreateRSADataSigner(PartnerPrivKey);
    NSString *signedString = [signer signString:orderInfo];
    return signedString;
}



////支付成功后跳入
-(void)refreshOrderConfirmStatus{
    OrderSuccessViewController * success = [[OrderSuccessViewController alloc] init];
    [self.navigationController pushViewController:success animated:YES];
}

//进入订单列表
- (void)goToOrderList{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[XDTools appDelegate].tabBarController confirmSelectTabBar:1];
    [[XDTools appDelegate].tabBarController setSelectedIndex:1];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
